<?php

/**
 * Adds a new device to the list of registered devices.
 * Invoked when the device connects to this script and posts its device token.
 * @author Andrew Pigram
 * @version 1.0
 * @package default
 */

/**
 * Add the device token to the database
 */
function addDevice() {
    // connect to the MySQL database
    $database = connectToDatabase();
    
    // extract the POST data
    $newDevice = $_POST["devtoken"];
    $user = $_POST["uid"];
    
    // update the relevant record with the device token using the POST data
    $database->query("DELETE FROM user_devices WHERE user_device_token='$newDevice'");
    $database->commit();
    $query = "INSERT INTO user_devices (user_id, user_device_type, user_device_token) VALUES ($user, 'iOS', '$newDevice')";
    $response = $database->query($query);
    $database->commit();
    
    if ($response == FALSE)
        echo "Error\n";
    
    // close the database
    $database->close();
}

/**
 * Connect to the ADODB database storing device tokens
 * @return mysqli The database object
 */
function connectToDatabase() {
    // establish a connection to the ADODB database
    return new mysqli("localhost", "rmplanne_andrew", "Pi39RQ", "rmplanne_rmplanner");
}

// add the device to the database
addDevice();

// echo success
echo "OK";
?>